package com.tenqian.media.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tenqian.CONSTANT;
import com.tenqian.Result;
import com.tenqian.media.domain.News;
import com.tenqian.media.service.MediaService;
import com.tenqian.utils.HttpClientUtils;
import com.tenqian.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class MediaServiceImpl implements MediaService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    static Logger logger = LoggerFactory.getLogger(MediaService.class);

    @Override
    public Result video_search(String q) throws Exception {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Accept-Language", "zh-CN");
        headerMap.put("Ocp-Apim-Subscription-Key", CONSTANT.BING_SUBSCRIPTIONKEY);
        JSONObject jsonObject = HttpClientUtils.httpGet(CONSTANT.BING_SEARCH_VIDEO_API + "?modules=All&q=" + q, headerMap);
        return ResultUtil.success(jsonObject);
    }

    @Override
    public Result news_get(String page, String size, String channel) {
        //每页数量
        int rows = Integer.parseInt(size);
        //先从缓存里取
        String s = redisTemplate.opsForValue().get("news:" + channel + "_" + page + "_" + size);
        if (StringUtils.isNotBlank(s)) {
            return ResultUtil.success(JSONArray.parseArray(s, News.class));
        }

        //计算start
        String start = (Integer.parseInt(page) - 1) * rows + "";
        //发送请求
        Map<String, String> queryMap = new HashMap();
        queryMap.put("channel", channel); //频道 "头条","新闻","财经","体育","娱乐","军事","教育","科技","NBA","股票","星座","女性","健康","育儿"
        queryMap.put("num", size); //
        queryMap.put("start", start); //开始位置 默认从0开始
        queryMap.put("appkey", CONSTANT.WX_NEWS_API_KEY); //访问参数
        JSONObject jsonObject = HttpClientUtils.httpGet(CONSTANT.WX_NEWS_API, queryMap, null);
        String list = jsonObject.getJSONObject("result").getJSONObject("result").getString("list");//新闻数组

        //缓存
        redisTemplate.opsForValue().set("news:" + channel + "_" + page + "_" + size, list, 1, TimeUnit.DAYS);
        //转为news集合
        return ResultUtil.success(JSONArray.parseArray(list, News.class));
    }

    @Override
    public Result hottestVideo(int page) {
        int pn = (page - 1) * 8;//8为固定不能改
        //从缓存里取
        String s1 = redisTemplate.opsForValue().get("hot_video:" + page);
        if (StringUtils.isNotBlank(s1)) {
            return ResultUtil.success(JSONArray.parseArray(s1));
        }
        String s = HttpClientUtils.httpGetReturnStr("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?" +
                "resource_id=28286&from_mid=1&&format=json&ie=utf-8" +
                "&oe=utf-8&query=%E7%94%B5%E5%BD%B1&sort_key=16" +
                "&sort_type=1&stat0=&stat1=&stat2=&stat3=" +
                "&rn=8&cb=ssssssssssssssssssssssssssss" +
                "&_=1511507831018&pn=" + pn);
        JSONObject result = JSONObject.parseObject(s.substring(s.indexOf("(") + 1, s.lastIndexOf(")")));
        JSONArray data = result.getJSONArray("data").getJSONObject(0).getJSONArray("result");
        List<Map> list = new ArrayList<>();
        for (Object datum : data) {
            JSONObject temp = (JSONObject) datum;
            Map<String, String> map = new HashMap<>();
            map.put("pic", temp.getString("kg_pic_url"));
            map.put("douban", temp.getString("additional"));
            map.put("title", temp.getString("ename"));
            list.add(map);
        }
        //缓存
        redisTemplate.opsForValue().set("hot_video:" + page, JSONArray.toJSONString(list), 3, TimeUnit.DAYS);
        return ResultUtil.success(list);
    }
}
